package contestseeker.data;

import contestseeker.action.TimeString;
import contestseeker.visitors.VisitorBase;

import java.util.Map;
import java.util.HashMap;

public class PageBuffer {
	private static Map<String, StringBuffer> tableMap = new HashMap<String, StringBuffer>();
	
	public static void clear()
	{
		tableMap.clear();
	}
	
	public static void append(VisitorBase visitor, StringBuffer strbuf)
	{
		append(visitor, strbuf.toString());
	}
	
	public static void append(VisitorBase visitor, String str)
	{
		if (!tableMap.containsKey(visitor.NAME))
			tableMap.put(visitor.NAME, new StringBuffer());
		StringBuffer tablebuf = tableMap.get(visitor.NAME);
		if (str.compareTo("Network is unreachable: connect") == 0
			|| str.compareTo("Connection timed out: connect") == 0)
			str = str + " CAUSED by <a href=" + visitor.URL + ">" + visitor.NAME + "</a><br />";
		tablebuf.append(str);
	}
	
	public static String toHTMLString(VisitorBase[] visitors)
	{
		StringBuffer page = new StringBuffer();
		page.append("<html>\n" +
					"<head>\n" +
					"<title>Contest Seeker Powered by rush</title>\n");
		page.append("</head>\n");
		page.append("<body>\n");
		page.append("<style>\n" +
				"tr.table_header { padding:0.1em 0.3em; background:#ccc; font-weight:bold; }\n" +
				"tr.row_odd { padding:0.2em 0.25em; background:#f3f3f3; border-bottom:1px solid #eaeaea; }\n" +
				"tr.row_even { padding:0.2em 0.25em; background:#eaeaea; border-bottom:1px solid #eaeaea; }\n" +
				"</style>\n");
		page.append("Create Time: " + TimeString.getTimeString() + "<br />\n");
		for (int i = 0; i < visitors.length; ++i)
			page.append(tableMap.get(visitors[i].NAME));
		page.append("</body>\n");
		page.append("</html>\n");
		return page.toString();
	}
	
	public static String toTableHTML(VisitorBase[] visitors)
	{
		StringBuffer page = new StringBuffer();
		page.append("<style>\n" +
				"tr.table_header { padding:0.1em 0.3em; background:#ccc; font-weight:bold; }\n" +
				"tr.row_odd { padding:0.2em 0.25em; background:#f3f3f3; border-bottom:1px solid #eaeaea; }\n" +
				"tr.row_even { padding:0.2em 0.25em; background:#eaeaea; border-bottom:1px solid #eaeaea; }\n" +
				"</style>\n");
		page.append("<p>Create Time: " + TimeString.getTimeString() + "</p>\n");
		for (int i = 0; i < visitors.length; ++i)
			page.append(tableMap.get(visitors[i].getClass().getName()));
		return page.toString();
	}
}
